//
//  CartListVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/17.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MJRefresh
import MBProgressHUD

class M_CartListVC: BaseViewControllerWithHeader,UITableViewDataSource,UITableViewDelegate {
    lazy var defultView : UIView = {
        let v = UIView()
        v.backgroundColor = .clear
        let img = v.drawImage(named: "gouwuchekong_117") { (make) in
            make.centerX.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        v.drawLabel(text: "购物车空", fontSize: 14, textColor: .x999999) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(img.snp.bottom).offset(10)
        }
        return v
    }()
    
    let btmtoolView = UIView()
    let sumLab = UILabel()
    
    var pageIndex = 1
    var pageSize = 20
    var totalSize = 2000
//    var cartListArr = [[String:Any?]]()
    
    var cartNoneArr = [[String:Any?]]()
    var cartZYArr = [[String:Any?]]()
    var cartJDArr = [[String:Any?]]()
    var zoneAry = LocalStorage.getAryToZone(forKey: ZoneCode105)
    var tableView = UITableView(frame: CGRect.zero, style: .grouped)
    let likeView = M_LikeView()
    
    let conutLab = UILabel()
    let ZYBtn = Button()
    let JDBtn = Button()
    
    let editView = UIView()
    let payAllBtn = Button()
    let selAllBtn = Button()
    let buyBtn = Button()
    var buyCount = 0
    
    var isSetupUI = false
    var isshowBack = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if !self.isSetupUI {
            self.setupUI()
        }
        refreshall()
        
        let name1 = NSNotification.Name(rawValue:PAY_SUCCEED)
        NotificationCenter.default.addObserver(self, selector: #selector(notfifica(sender:)), name: name1, object: nil)
        let name2 = NSNotification.Name(rawValue:CAR_CHANGE)
        NotificationCenter.default.addObserver(self, selector: #selector(notfifica(sender:)), name: name2, object: nil)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    func getDataList(pageIndex: Int, pageSize:Int, callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "pageIndex":pageIndex,
                                    "pageSize":pageSize]
        API.request(url: .M_GetCartList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                //刷新时清空数据
                self.cartJDArr = []
                self.cartZYArr = []
                self.cartNoneArr = []
                self.ZYBtn.isSelected = false
                self.JDBtn.isSelected = false
                self.selAllBtn.isSelected = false
                self.payAllBtn.isSelected = false
                
                if let dl = result.data?.getDictionary("data") {
                    for item in dl.getDictList("items") ?? [] {
                        if !(item.getBool("isShow") ?? false) {
                            self.cartNoneArr.append(item)
                        }
                        else if item.getString("zoneCode")?.contains("105002") ?? false {
                            self.cartJDArr.append(item)
                        }
                        else if item.getString("zoneCode")?.contains("105001") ?? false {
                            self.cartZYArr.append(item)
                        }
                        
                    }
                    self.pageIndex = dl.getInt("pageIndex") ?? 0
//                    self.pageSize = dl.getInt("pageSize") ?? 0
                    self.totalSize = dl.getInt("totalSize") ?? 0

                    let count = self.cartNoneArr.count + self.cartZYArr.count + self.cartJDArr.count
                    let strc = "(" + (anyToString(count) ?? "0") + ")"
                    self.conutLab.text = "购物车" + strc
                    self.queryData()
                    self.getBuyCount()
                }
                callback()
            }
        }
    }
    
    func setDataNum(cartID: String, productNum:Int ,callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "cartID":cartID,
                                    "productNum":productNum]
        API.request(url: .M_UpdateProductCartNum, params: params) { (result) in
            
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
            else {
                let popup = PopupSureBox(title: result.errMsg ?? "编辑失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    
    func delData(cartIDs: [String], callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "cartIDs":cartIDs]
        API.request(url: .M_DeleteProductCart, params: params) { (result) in
            
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
            else {
                let popup = PopupSureBox(title: result.errMsg ?? "删除失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
}

// MARK: UI
extension M_CartListVC {
    func setupUI() {
        isSetupUI = true
        headView.drawImage(named: "lepaidui_2") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton.snp.centerY)
        }
        backButton.isHidden = true
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        

        
        if isshowBack {
            headView.drawLabel(label: conutLab, text: "购物车", fontSize: 17, textColor: .x333333) { (make) in
                make.centerY.equalTo(backButton.snp.centerY)
                make.left.equalToSuperview().offset(22)
            }
            let returnButton = headView.drawButton(imageNamed: "L_Back") { (make) in
                make.centerY.equalTo(backButton.snp.centerY)
                make.left.equalToSuperview().offset(10)
            }
            returnButton.hitEdgInsets = .init(top: -10, left: -10, bottom: -10, right: -100)
            returnButton.addTarget(self, action: #selector(_fanhuiButtonClick(button:)), for: .touchUpInside)
        }else{
            headView.drawLabel(label: conutLab, text: "购物车", fontSize: 17, textColor: .x333333) { (make) in
                make.centerY.equalTo(backButton.snp.centerY)
                make.left.equalToSuperview().offset(10)
            }
        }
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        let btn = drawRightButton(title: "编辑")
        btn.addTarget(self, action: #selector(_wanchengButtonClick(button:)), for: .touchUpInside)
        btn.setTitle("完成", for: .selected)
        
        headView.drawView { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }.backgroundColor = .xF0F0F0
        
        let btm = 50
        ///底部工具条部分
        safeView.drawView(view: btmtoolView) { (make) in
            make.bottom.equalToSuperview().offset(btm)
            make.left.right.equalToSuperview()
            make.height.equalTo(100)
        }
        btmtoolView.backgroundColor = .white
        
        btmtoolView.drawButton(button: buyBtn,title: "结算(0)", titleColor: .white, fontSize: 14) { (make) in
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo(90)
        }
        buyBtn.backgroundColor = .xFC4C02
        buyBtn.addTarget(self, action: #selector(_buyButtonClick(button:)), for: .touchUpInside)
        
        //画横线
        let line = btmtoolView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(49)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        btmtoolView.drawButton(button: payAllBtn,imageNamed: "weixuanzhong_30") { (make) in
            make.centerY.equalTo(buyBtn)
            make.left.equalToSuperview().offset(10)
        }
        payAllBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -80)
        payAllBtn.setImage(UIImage.init(named: "xuanzhong_31"), for: .selected)
        payAllBtn.addTarget(self, action: #selector(_selAllButtonClick(button:)), for: .touchUpInside)
        btmtoolView.drawLabel(text: "全选", fontSize: 12, textColor: .x999999) { (make) in
            make.centerY.equalTo(payAllBtn)
            make.left.equalTo(payAllBtn.snp.right).offset(10)
        }
        
        let dl = LocalStorage.getDic(forKey: DEFULT_MALL)
        let centUnitName = dl?.getString("centName")
        let lab = btmtoolView.drawLabel(text: centUnitName, fontSize: 13, textColor: .x666666) { (make) in
            make.right.equalTo(buyBtn.snp.left).offset(-10)
            make.centerY.equalTo(payAllBtn)
        }
        
        btmtoolView.drawLabel(label: sumLab,text: "0", fontSize: 18, textColor: .xFC4C02) { (make) in
            make.right.equalTo(lab.snp.left).offset(-10)
            make.centerY.equalTo(payAllBtn)
            make.height.equalTo(45)
        }
        sumLab.numberOfLines = 0
        sumLab.preferredMaxLayoutWidth = 100
        
        btmtoolView.drawLabel(text: "合计:", fontSize: 14, textColor: .x333333) { (make) in
            make.right.equalTo(sumLab.snp.left).offset(-5)
            make.bottom.equalTo(payAllBtn)
        }
        
        ///底部工具条部分（编辑状态）
        safeView.drawView(view: editView) { (make) in
            make.bottom.equalToSuperview().offset(btm)
            make.left.right.equalToSuperview()
            make.height.equalTo(100)
        }
        editView.backgroundColor = .white
        editView.isHidden = true
        
        //画横线
        let line1 = editView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(49)
            make.height.equalTo(1)
        }
        line1.backgroundColor = .xF2F2F2
        
        let delBtn = editView.drawButton(title: "删除", titleColor: .white, fontSize: 14) { (make) in
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo(90)
        }
        delBtn.backgroundColor = .xFC4C02
        delBtn.addTarget(self, action: #selector(_delButtonClick(button:)), for: .touchUpInside)
        
        editView.drawButton(button: selAllBtn,imageNamed: "weixuanzhong_30") { (make) in
            make.top.equalToSuperview().offset(15)
            make.left.equalToSuperview().offset(10)
        }
        selAllBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -80)
        selAllBtn.setImage(UIImage.init(named: "xuanzhong_31"), for: .selected)
        selAllBtn.addTarget(self, action: #selector(_selAllButtonClick(button:)), for: .touchUpInside)
        editView.drawLabel(text: "全选", fontSize: 12, textColor: .x999999) { (make) in
            make.centerY.equalTo(delBtn)
            make.left.equalTo(selAllBtn.snp.right).offset(10)
        }

        //添加列表
        safeView.addSubview(tableView)
        tableView.backgroundColor = UIColor.clear;
        tableView.register(M_CartCell.self, forCellReuseIdentifier: "M_CartCell")
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.allowsMultipleSelection = true
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(btmtoolView.snp.top)
        }
        let _ = getRefreshHeader()
        
        initKeyboardObserver()
    }

        func getRefreshHeader()->MJRefreshHeader {
    //        顶部的下拉初始化
            let header = MJRefreshNormalHeader()
            header.lastUpdatedTimeLabel.isHidden = true
            tableView.mj_header = header
            header.setTitle("下拉刷新...", for: .idle)
            header.setTitle("下拉刷新...", for: .pulling)
            header.setTitle("下拉更新中...", for: .refreshing)
            header.setTitle("完成...", for: .willRefresh)
            header.setTitle("下拉刷新...", for: .noMoreData)
            header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

    //        顶部的处理逻辑：
            return tableView.mj_header!
        }
        
        func getRefreshFooter()->MJRefreshFooter {
            if tableView.mj_footer == nil {
                //        底部初始化：
                let footer = MJRefreshBackNormalFooter()
    //            footer.isOnlyRefreshPerDrag = true
                tableView.mj_footer = footer
                footer.setTitle("上拉更多...", for: .idle)
                footer.setTitle("上拉更多...", for: .pulling)
                footer.setTitle("下拉更新中...", for: .refreshing)
                footer.setTitle("完成...", for: .willRefresh)
                footer.setTitle("没有了...", for: .noMoreData)
                footer.setRefreshingTarget(self, refreshingAction: #selector(onFooterLoadMore))
            }

    //        底部处理逻辑：
            if pageIndex * pageSize < totalSize {
                tableView.mj_footer.endRefreshing()
            }
            else {
                tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
    //        底部数据加载
             return tableView.mj_footer!
        }
}

// MARK: event & action
extension M_CartListVC {
    
    @objc func notfifica(sender:NSNotification) {
        getDataList(pageIndex: 1, pageSize: 1000, callback: {
            if self.cartZYArr.count > 0 {
                self.tableView.scrollToRow(at: .init(row: 0, section: 0), at: .top, animated: false)
            }
            else if self.cartJDArr.count > 0 {
                self.tableView.scrollToRow(at: .init(row: 0, section: 1), at: .top, animated: false)
            }
            else if self.cartNoneArr.count > 0 {
                self.tableView.scrollToRow(at: .init(row: 0, section: 2), at: .top, animated: false)
            }
        })
    }
    
    func queryData(_ showDefult:Bool=true) {
        tableView.reloadData()
        sumData()
    }
    
    func getSelectedRows() -> [IndexPath]? {
        var indexPaths:[IndexPath] = []
        if cartZYArr.count > 0 {
            for i in 0...cartZYArr.count-1{
                if cartZYArr[i].getBool("isSelected") ?? false {
                    indexPaths.append(.init(row: i, section: 0))
                }
            }
        }
        
        if cartJDArr.count > 0 {
            for i in 0...cartJDArr.count-1{
                if cartJDArr[i].getBool("isSelected") ?? false {
                    indexPaths.append(.init(row: i, section: 1))
                }
            }
        }
        return indexPaths
    }
    
    func getBuyCount() {
        buyCount = 0
        for dic in cartZYArr {
            if dic.getBool("isSelected") ?? false {
                buyCount += dic.getInt("productNum") ?? 1
            }
        }
        for dic in cartJDArr {
            if dic.getBool("isSelected") ?? false {
                buyCount += dic.getInt("productNum") ?? 1
            }
        }
        buyBtn.setTitleAndColor(title: "结算(" + anyToString(buyCount)! + ")", color: .white)
    }
    
    func sumData() {
        var sum = 0.0
        guard let indexPaths = getSelectedRows() else { return sumLab.text = anyToString(sum)}
        for indexPath in indexPaths {
            var dic : [String:Any?]?
            switch indexPath.section {
            case 0:
                dic = cartZYArr[indexPath.row]
            case 1:
                dic = cartJDArr[indexPath.row]
            default:
                break
            }
            let p = anyToDouble(dic?["productPrice"]!) ?? 0
            let n = anyToDouble(dic?["productNum"]!) ?? 0
            sum += p*n
        }
        sumLab.text = anyToString(sum.round2)?.quXiaoShuDianHouDeLing
    }
    
    func refreshall() {
        getDataList(pageIndex: 1, pageSize: 1000, callback: {
            
        })
    }
    
    @objc func _selAllButtonClick(button: Button) {
        button.isSelected = !button.isSelected
        if button.isSelected {
            ZYBtn.isSelected = false
            _ZYquanxuanButtonClick(button: ZYBtn)
            JDBtn.isSelected = false
            _JDquanxuanButtonClick(button: JDBtn)
        }
        else {
            ZYBtn.isSelected = true
            _ZYquanxuanButtonClick(button: ZYBtn)
            JDBtn.isSelected = true
            _JDquanxuanButtonClick(button: JDBtn)
        }
    }
    
    @objc func _delButtonClick(button: Button) {
        
        let popup = PopupConfirmBox(info: "是否删除", title: "")
        popup.show(vc: UIViewController.topMostController() ?? self)
        popup.onSureButtonClick = {
            LocalStorage.saveString("", forKey: LOGIN_PASSWORD)
            //确定执行
            
            var delitems = [String]()
            guard let indexPaths = self.getSelectedRows() else { return }
            for indexPath in indexPaths {
                var dic : [String:Any?]?
                switch indexPath.section {
                case 0:
                    dic = self.cartZYArr[indexPath.row]
                case 1:
                    dic = self.cartJDArr[indexPath.row]
                default:
                    break
                }
                let item = dic?.getString("cartID") ?? ""
                delitems.append(item)
            }
            
            if delitems.count > 0 {
                self.delData(cartIDs: delitems, callback: {
                    if self.selAllBtn.isSelected {
                        let popup = PopupBox(infoText: "商品清除成功")
                        popup.show(vc: UIViewController.topMostController() ?? self)
                    }
                    else {
                        let popup = PopupBox(infoText: "商品删除成功")
                        popup.show(vc: UIViewController.topMostController() ?? self)
                    }
                    
                    self.refreshall()
                })
            }
        }
    }
    
    @objc func _buyButtonClick(button: Button) {
        var productInfo = [[String:Any?]]()
        var items = [[String:Any?]]()
        guard let indexPaths = getSelectedRows() else { return }
        var hassection = [Int:Any?]()
        for indexPath in indexPaths {
            hassection.updateValue(anyToString(indexPath.section), forKey: indexPath.section)
            var dic : [String:Any?]?
            switch indexPath.section {
            case 0:
                dic = cartZYArr[indexPath.row]
            case 1:
                dic = cartJDArr[indexPath.row]
            default:
                break
            }
            let item = ["cartID": dic?.getString("cartID") ?? ""]
            items.append(item)
            productInfo.append(dic ?? [:])
        }
        
        if hassection.keys.count == 1 {
            let orderData = OrderDataClass(fromDictionary: ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                                            "orderDeliverModeCode":"",
                                                            "orderDeliverSiteCode":"",
                                                            "zoneCode": "105001",
                                                            "remark": "留言",
                                                            "items":items])
            let vc = M_OrderVC(orderData, info: productInfo)
            vc.iscar = true
            pushViewController(vc)
        }
        else if hassection.keys.count == 0 {
            let popup = PopupBox(infoText: "您还没有选择商品")
            popup.show(vc: UIViewController.topMostController() ?? self)
        }
        else {
            let vc = UIViewController.topMostController() ?? self
            
            let pview = M_CartListPayView()
            pview.productInfo = productInfo
            pview.backgroundColor = .clear
            vc.view.drawView(view: pview, { (make) in
                make.left.right.bottom.top.equalToSuperview()
            })
            pview.callPayBlock(block: { (type) in
                items = [[String:Any?]]()
                if type == 105002 {
                    for dic in pview.JDAry {
                        let item = ["cartID": dic.getString("cartID") ?? ""]
                        items.append(item)
                    }

                    let orderData = OrderDataClass(fromDictionary: ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                                                    "orderDeliverModeCode":"",
                                                                    "orderDeliverSiteCode":"",
                                                                    "zoneCode": "105001",
                                                                    "remark": "留言",
                                                                    "items":items])
                    let vc = M_OrderVC(orderData, info: pview.JDAry)
                    vc.iscar = true
                    self.pushViewController(vc)
                }
                else {
                    for dic in pview.ZYAry {
                        let item = ["cartID": dic.getString("cartID") ?? ""]
                        items.append(item)
                    }

                    let orderData = OrderDataClass(fromDictionary: ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                                                    "orderDeliverModeCode":"",
                                                                    "orderDeliverSiteCode":"",
                                                                    "zoneCode": "105001",
                                                                    "remark": "留言",
                                                                    "items":items])
                    let vc = M_OrderVC(orderData, info: pview.ZYAry)
                    vc.iscar = true
                    self.pushViewController(vc)
                }
            })
//            let popup = PopupSureBox(title: "不同专区的商品无法结算！", infoText: "", sureText: "确定")
//            popup.show(vc: UIViewController.topMostController() ?? self)
//            popup.onSureButtonClick = {
//            }
        }
    }
    
    @objc func onHeaderRequery() {
        //        顶部数据重新加载
//        getRefreshFooter().state = .idle
        tableView.mj_header.endRefreshing()
        refreshall()
    }
    
    @objc func onFooterLoadMore() {
        //        底部数据重新加载更多底部处理逻辑：
        if pageIndex * pageSize < totalSize {
            tableView.mj_footer.endRefreshing()
        }
        else {
            tableView.mj_footer.endRefreshingWithNoMoreData()
        }
    }
    
    @objc func _fanhuiButtonClick(button: Button) {
        popViewController()
    }
    
    @objc func _wanchengButtonClick(button: Button) {
        button.isSelected = !button.isSelected
        editView.isHidden = !button.isSelected
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    
    @objc func _ZYquanxuanButtonClick(button: Button) {
        button.isSelected = !button.isSelected
        if cartZYArr.count == 0 {
            return
        }
        for i in 0...cartZYArr.count-1{
            let indexpath = IndexPath(row: i, section: 0)
            self.cartZYArr[indexpath.row].updateValue(button.isSelected, forKey: "isSelected")
            tableView.reloadData()
        }
        if !button.isSelected {
            self.payAllBtn.isSelected = false
            self.selAllBtn.isSelected = false
        }
        sumData()
        getBuyCount()
    }
    
    @objc func _JDquanxuanButtonClick(button: Button) {
        button.isSelected = !button.isSelected
        if cartJDArr.count == 0 {
            return
        }
        for i in 0...cartJDArr.count-1{
            let indexpath = IndexPath(row: i, section: 1)
            self.cartJDArr[indexpath.row].updateValue(button.isSelected, forKey: "isSelected")
            tableView.reloadData()
        }
        if !button.isSelected {
            self.payAllBtn.isSelected = false
            self.selAllBtn.isSelected = false
        }
        sumData()
        getBuyCount()
    }
    
    @objc func _qingkongButtonClick(button: Button) {
        var ids = [String]()
        for item in self.cartNoneArr {
            ids.append(item.getString("cartID") ?? "")
        }
        self.showConfirm(content: "清空所有失效商品吗？", onSure: {
            self.delData(cartIDs: ids, callback: {
                self.cartNoneArr = []
                self.tableView.reloadData()
            })
        })
    }
    
    ///MARK: UITableViewDataSource
    //尾部高度
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section != 2 || likeView.productListArr.count == 0 {
            return 20
        }
        
        var rownum = Double(likeView.productListArr.count)/2
        rownum = ceil(rownum)
        return CGFloat(260*rownum+52)
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section != 2 {
            return nil
        }
        else if likeView.productListArr.count == 0 && isSetupUI {
            likeView.getDataList(zoneCode: "105001", pageIndex: 1, pageSize: 10, callback: { (conut) in
                if conut > 0 {
                    self.queryData(false)
                }
            })
            return nil
        }
        
        let bgview = UIView()
        bgview.backgroundColor = .white
        bgview.drawView(view: likeView) {(make) in
            make.top.left.right.bottom.equalToSuperview()
        }
        likeView.callselBlock { (info) in
            let vc = M_ProductDetailVC(info: info)
            self.pushViewController(vc)
        }
        return bgview
    }
    
    //头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
            case 0:
            if cartJDArr.count == 0,cartZYArr.count == 0,cartNoneArr.count == 0 {
                return 200
            }
            else if cartZYArr.count == 0 {
                return 0
            }
            else {
                return 55
            }
            case 1:
            if cartJDArr.count == 0 {
                return 0
            }
            else {
                return 55
            }
            case 2:
            if cartNoneArr.count == 0 {
                return 0
            }
            else {
                return 55
            }
        default:
            return 0
        }
    }
    
    //加载section头部
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let thview = UIView()
        thview.backgroundColor = .white
        switch section {
        case 0:
        if cartJDArr.count == 0,cartZYArr.count == 0,cartNoneArr.count == 0 {
            thview.backgroundColor = .xF2F2F2
            thview.drawView(view: defultView, { (make) in
                make.left.right.top.bottom.equalToSuperview()
            })
        }
        else {
            thview.drawButton(button: ZYBtn,imageNamed: "weixuanzhong_30") { (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(10)
            }
            ZYBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
            ZYBtn.setImage(UIImage.init(named: "xuanzhong_31"), for: .selected)
            ZYBtn.addTarget(self, action: #selector(_ZYquanxuanButtonClick(button:)), for: .touchUpInside)
            thview.drawImage(named: "zhiyingdianpu_33") { (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(38.5)
            }
            thview.drawLabel(text: "自营专区", fontSize: 15, textColor: .x333333) { (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(64.5)
            }
        }
        case 1:
            thview.drawButton(button: JDBtn,imageNamed: "weixuanzhong_30") { (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(10)
            }
            JDBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
            JDBtn.setImage(UIImage.init(named: "xuanzhong_31"), for: .selected)
            JDBtn.addTarget(self, action: #selector(_JDquanxuanButtonClick(button:)), for: .touchUpInside)
            thview.drawImage(named: "jdong_34") { (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(38.5)
            }
            thview.drawLabel(text: "京东配送", fontSize: 15, textColor: .x333333) { (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(64.5)
            }
        case 2:
            
            let num = anyToString(cartNoneArr.count) ?? "0"
            thview.drawLabel(text: "失效商品"+num+"件", fontSize: 15, textColor: .x333333) { (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(45)
            }
            let btn = thview.drawButton(title: "清空失效商品", titleColor: .xFC4C02, fontSize: 12) { (make) in
                make.centerY.equalToSuperview()
                make.right.equalToSuperview().offset(-10)
            }
            btn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
            btn.addTarget(self, action: #selector(_qingkongButtonClick(button:)), for: .touchUpInside)
        default:
            break
        }
        //画横线
        let line = thview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        return thview
    }
    
    //组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return cartZYArr.count

        case 1:
            return cartJDArr.count

        case 2:
            return cartNoneArr.count
            
        default:
            return 0
        }
    }
    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "M_CartCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellid) as? M_CartCell
        if cell==nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellid) as? M_CartCell
            cell?.selectionStyle = .none
        }
        
        switch indexPath.section {
        case 0:
               cell?.celldata = cartZYArr[indexPath.row]
               cell?.nonePro = false
               cell?.callselBlock {
                   self.cartZYArr[indexPath.row].updateValue(cell?.selImg.isSelected, forKey: "isSelected")
                   self.sumData()
                   if !(cell?.selImg.isSelected ?? false) {
                       self.ZYBtn.isSelected = false
                   }
                   else {
                    var isSel = true
                    for dic in self.cartZYArr {
                        if !(dic.getBool("isSelected") ?? false) {
                            isSel = false
                        }
                    }
                    self.ZYBtn.isSelected = isSel
                  }
                  if !self.ZYBtn.isSelected {
                      self.payAllBtn.isSelected = false
                      self.selAllBtn.isSelected = false
                  }
                  self.getBuyCount()
               }
        case 1:
               cell?.celldata = cartJDArr[indexPath.row]
               cell?.nonePro = false
               cell?.callselBlock {
                   self.cartJDArr[indexPath.row].updateValue(cell?.selImg.isSelected, forKey: "isSelected")
                   self.sumData()
                   if !(cell?.selImg.isSelected ?? false) {
                       self.JDBtn.isSelected = false
                   }
                    else {
                     var isSel = true
                     for dic in self.cartJDArr {
                         if !(dic.getBool("isSelected") ?? false) {
                             isSel = false
                         }
                     }
                     self.JDBtn.isSelected = isSel
                   }
                   if !self.JDBtn.isSelected {
                       self.payAllBtn.isSelected = false
                       self.selAllBtn.isSelected = false
                   }
                   self.getBuyCount()
               }
        case 2:
               cell?.celldata = cartNoneArr[indexPath.row]
               cell?.nonePro = true
        default:
            break
        }
        cell?.callEditBlock { (n) in
            self.setDataNum(cartID: cell?.celldata?.getString("cartID") ?? "", productNum: n, callback: {
                self.refreshall()
            })
            self.getBuyCount()
        }
        cell?.calldetailBlock {
            let vc = M_ProductDetailVC(info: cell?.celldata ?? [:])
            self.pushViewController(vc)
        }
        
        fillAccessoryToolBar(target: cell)
        return cell!
    }
    ///MARK: UITableViewDelegate
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
    }
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        print(indexPath.row)
    }
    
    //左划状态
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let del = UITableViewRowAction(style: .default, title: "删除") { action, index in
            // 当点击了删除按钮
            var curary : [[String : Any?]]
            switch indexPath.section {
                case 0:
                    curary = self.cartZYArr
                case 1:
                    curary = self.cartJDArr
                case 2:
                    curary = self.cartNoneArr
                default:
                    curary = []
            }

            let popup = PopupConfirmBox(info: "确定删除该商品？", title: "温馨提示")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
                self.delData(cartIDs: [curary[indexPath.row].getString("cartID") ?? ""], callback: {
                    switch indexPath.section {
                    case 0:
                        // 当点击了删除按钮
                        self.cartZYArr.remove(at: indexPath.row)
                    case 1:
                        // 当点击了删除按钮
                        self.cartJDArr.remove(at: indexPath.row)
                    case 2:
                        // 当点击了删除按钮
                        self.cartNoneArr.remove(at: indexPath.row)
                        
                    default:
                        break
                    }
                    // 刷新
                    tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.bottom)
                })
                self.sumData()
            }
            popup.onCancelButtonClick = {
//                tableView.reloadData()
            }
        }
        del.backgroundColor = .xFC4C02
        return [del]
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
         return false
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
    }
}
